﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		CaptchaValidateFilter.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 // 
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System.Web.Mvc;
using Dexter.Dependency;
using Dexter.Services;
using Recaptcha;

namespace Dexter.Web.Mvc.Filters {
	public class CaptchaValidateFilter : ActionFilterAttribute {
		const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
		const string RESPONSE_FIELD_KEY = "recaptcha_response_field";

		/// <summary>
		/// Gets the configuration.
		/// </summary>
		/// <value>The configuration.</value>
		public IConfigurationService Configuration {
			get { return DexterContainer.Resolve <IConfigurationService> ( ); }
		}

		/// <summary>
		/// 	Called by the MVC framework before the action method executes.
		/// </summary>
		/// <param name = "filterContext">The filter context.</param>
		public override void OnActionExecuting ( ActionExecutingContext filterContext ) {
			bool isValid;

			var siteConfiguration = Configuration.Configuration;

			if ( !siteConfiguration.AntispamConfiguration.ReCaptchaConfiguration.Enable ) {
				isValid = true;
			}
			else {
				string captchaChallengeValue = filterContext.HttpContext.Request.Form[ CHALLENGE_FIELD_KEY ];
				string captchaResponseValue = filterContext.HttpContext.Request.Form[ RESPONSE_FIELD_KEY ];
				RecaptchaValidator captchaValidtor = new RecaptchaValidator {
					PrivateKey = siteConfiguration.AntispamConfiguration.ReCaptchaConfiguration.PrivateKey ,
					RemoteIP = filterContext.HttpContext.Request.UserHostAddress ,
					Challenge = captchaChallengeValue ,
					Response = captchaResponseValue
				};

				RecaptchaResponse recaptchaResponse = captchaValidtor.Validate ( );
				isValid = recaptchaResponse.IsValid;
			}

			// this will push the result value into a parameter in our Action
			filterContext.ActionParameters[ "captchaValid" ] = isValid;

			base.OnActionExecuting ( filterContext );
		}
	}
}
